//
//  FileViewController.m
//  e律师
//
//  Created by 韦淋 on 2017/5/18.
//  Copyright © 2017年 test. All rights reserved.
//

#import "FileViewController.h"


#define RGBCOLOR(HEX)     [UIColor colorWithRed:((((HEX)>>16)&0xFF))/255. green:((((HEX)>>8)&0xFF))/255.  blue:((((HEX)>>0)&0xFF))/255. alpha:1]

@interface FileViewController ()<LynnTypeButtonActionDelegate,UITableViewDelegate,UITableViewDataSource,FileCellActionDelegate>

@property (nonatomic, strong) UITableView *fileTableView;
@property (nonatomic, strong) UIButton *barAddButton;
@property (nonatomic, strong) NSMutableArray *clubhouseFile;
@property (nonatomic, strong) NSMutableArray *personalFile;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, assign) NSInteger typeFlag;
@property (nonatomic, strong) NSString *roleName;
@end

@implementation FileViewController
- (void)viewWillAppear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = false;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.view.backgroundColor = [UIColor whiteColor];
    self.clubhouseFile = [NSMutableArray array];
    self.personalFile = [NSMutableArray array];
    self.dataSource = [NSMutableArray array];
    self.typeFlag = 0;
    [self initUI];
    [self getCaseFile];
}

- (void)initUI{
    LynnTypeButtonView  *typeBtnView = [[LynnTypeButtonView  alloc]initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 44)];
    [typeBtnView setTypeButtonTitles:@[@"会所文件",@"个人文件"] withDownLableHeight:2 andDeleagte:self];
    

    [typeBtnView setTypeButtonNormalColor:[UIColor blackColor] andSelectColor:[UIColor colorWithRed:33.0f/255.0f green:180.0f/255.0f blue:237.0f/255.0f alpha:1.0f]];
    typeBtnView.backgroundColor = [UIColor whiteColor];
    [self.view insertSubview:typeBtnView atIndex:0];
    [self.view insertSubview:self.fileTableView belowSubview:typeBtnView];
    [self.view addSubview:self.barAddButton];
    
}
- (void)loadNewData{
    [self.dataSource removeAllObjects];
    [self getCaseFile];
}
- (void)getCaseFile{
    // 创建信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        
        // 请求一
        [NetworkingManager getUrl:[NSString stringWithFormat:@"%@user_id=%@",QUERYPOST_URL,[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"]] dic:nil Succeed:^(id responseData) {
            NSLog(@"success : %@",responseData);
            self.roleName = responseData[@"result"][0][@"name"];
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            NSLog(@"error : %@",error);
            [MBProgressHUD showError:@"网络异常"];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    });
    dispatch_group_async(group, queue, ^{
        
        // 请求二
        [NetworkingManager getUrl:[NSString stringWithFormat:@"%@createid=%@",CASEFILE_URL,[InfoSingleTon personInfoSingleTon].infoDic[@"user"][@"id"]] dic:nil Succeed:^(id responseData) {
            NSLog(@"success : %@",responseData);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            for (NSDictionary *dic  in responseData[@"result"]) {
                if ([dic[@"gsid"] integerValue] == -1) {
                    [self.personalFile addObject:dic];
                }
                else{
                    [self.clubhouseFile addObject:dic];
                }
            }
            if (self.typeFlag == 0) {
                self.dataSource = self.clubhouseFile;
            }else if (self.typeFlag == 1){
                self.dataSource = self.personalFile;
            }
            if (self.dataSource.count == 0){
                [MBProgressHUD showSuccess:@"暂无更多数据"];
            }
            dispatch_semaphore_signal(semaphore);
        } failure:^(NSError *error) {
            [MBProgressHUD showError:@"网络异常"];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    });
    
    dispatch_group_notify(group, queue, ^{
        
        // 三个请求对应三次信号等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        //在这里 进行请求后的方法，回到主线程
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //更新UI操作
            NSLog(@"wancheng");
            
            [self.fileTableView reloadData];
            NSLog(@"fileData1 = %@",self.clubhouseFile);
            NSLog(@"fileData = %@",self.personalFile);
            NSLog(@"fileData3 = %@",self.dataSource);
            [self.fileTableView.mj_header endRefreshing];
            
        });
    });
}

- (void)action_AddFile:(UIButton *)sender{
    NSLog(@"添加文件 ");
    PostFileViewController *postFileVC = [[PostFileViewController alloc] init];
    [self.navigationController pushViewController:postFileVC animated:YES];
}
#pragma mark - FileCellButtonDelegate
- (void)didClickDownloadButtonAction:(UIButton *)sender{
    NSLog(@"下载 %ld",sender.tag);
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [NetworkingManager getUrl:[NSString stringWithFormat:@"%@%@",DOWNLOADFILE_URL,self.dataSource[sender.tag][@"xzdz"]] dic:nil Succeed:^(id responseData) {
        NSLog(@"success ： %@",responseData);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSError *error) {
        NSLog(@"error : %@",error);
        [MBProgressHUD showError:@"网络异常"];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    }];
}
- (void)didClickDeleteButtonAction:(UIButton *)sender{
    if (![self.roleName isEqualToString:@"主任"]) {
        [MBProgressHUD showError:@"无权限删除会所文件"];
    }else{
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        NSLog(@"删除 %ld",sender.tag);
        NSString *fileId = [NSString stringWithFormat:@"%ld",sender.tag - 200];
        [NetworkingManager getUrl:[NSString stringWithFormat:@"%@&id=%@",DELETEFILE_URL,fileId] dic:nil Succeed:^(id responseData) {
            [self loadNewData];
        } failure:^(NSError *error) {
            [MBProgressHUD showError:@"网络错误"];
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        }];
    }
}
#pragma mark - TypeButtonDelegate
//实现代理
-(void)didClickTypeButtonAction:(UIButton*)button withIndex:(NSInteger)index
{
    self.typeFlag = index;
    [self.clubhouseFile removeAllObjects];
    [self.personalFile removeAllObjects];
    [self.dataSource removeAllObjects];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self.fileTableView reloadData];
    [self getCaseFile];
}
#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 160;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (self.typeFlag == 0) {
        return self.clubhouseFile.count;
    }
    else{
        return self.personalFile.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    FileCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FileCell" forIndexPath:indexPath];
    cell.delegate = self;
    cell.titleLable.text = self.dataSource[indexPath.row][@"newwjm"];
    cell.taddyNameLable.text = [NSString stringWithFormat:@"上传人姓名： %@",self.dataSource[indexPath.row][@"createname"]];
    cell.uploadTimeLable.text = [NSString stringWithFormat:@"上传时间： %@",self.dataSource[indexPath.row][@"createtime"]];
    cell.downLoadButton.tag = indexPath.row;
    cell.deleteButton.tag = [self.dataSource[indexPath.row][@"id"] integerValue] + 200;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
    return cell;
}
#pragma mark - Getter

- (UITableView *)fileTableView{
    if (!_fileTableView) {
        _fileTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 120, self.view.bounds.size.width, self.view.bounds.size.height - 120) style:UITableViewStylePlain];
        _fileTableView.backgroundColor = [UIColor clearColor];
        _fileTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _fileTableView.delegate = self;
        _fileTableView.dataSource = self;
        _fileTableView.estimatedRowHeight = 180;
        [_fileTableView registerClass:[FileCell class] forCellReuseIdentifier:@"FileCell"];
        _fileTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    }
    return _fileTableView;
}
- (UIButton *)barAddButton{
    if (!_barAddButton) {
        _barAddButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _barAddButton.frame = CGRectMake(330, 25, 30, 30);
        [_barAddButton setBackgroundImage:[UIImage imageNamed:@"jiahao"] forState:UIControlStateNormal];
        [_barAddButton addTarget:self action:@selector(action_AddFile:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _barAddButton;
}


@end
